#!/bin/bash

set -e

PERSISTENT_DATA_DIR="/var/lib/hive-metastore"
INIT_FLAG_FILE="$PERSISTENT_DATA_DIR/.init_done"

if [ "${SERVICE_NAME}" = "metastore" ]; then
  # 检查元数据库是否已初始化
  if [ -f "$INIT_FLAG_FILE" ]; then
    echo "Metastore schema already initialized (flag file exists). Skipping."
  else
    echo "Checking metastore schema status..."
    
    # 使用 schematool 验证元数据状态
    if schematool -dbType mysql -info; then
      echo "Metastore schema already exists. Skipping initialization."
      touch "$INIT_FLAG_FILE"
    else
      echo "Initializing Hive Metastore Schema..."
      if schematool -dbType mysql -initSchema --verbose; then
        touch "$INIT_FLAG_FILE"
        echo "Metastore schema initialized successfully."
      else
        echo "Error initializing metastore schema. Attempting repair..."
        
        # 尝试升级而非初始化
        if schematool -dbType mysql -upgradeSchema --verbose; then
          touch "$INIT_FLAG_FILE"
          echo "Schema upgrade successful after initialization failure."
        else
          echo "Schema upgrade failed. Manual intervention required."
          exit 1
        fi
      fi
    fi
  fi
fi

# 启动服务
if [ "${SERVICE_NAME}" = "metastore" ]; then
  hive --service metastore
elif [ "${SERVICE_NAME}" = "hiveserver2" ]; then
  hive --service hiveserver2
else
  exec "$@"
fi
